/*
 * @Author: ZhaoZhiqi
 * @Date: 2022-08-09 09:47:21
 * @LastEditors: ZhaoZhiqi
 * @LastEditTime: 2022-12-12 18:28:28
 * @Description: 接口封装
 * @FilePath: \tuanfeng-admin-front\src\utils\request.ts
 */

import axios, { Method } from "axios";
import { ElNotification } from 'element-plus';
import router from "../router";

const service = axios.create({
    baseURL: `${import.meta.env.VITE_APP_HTTPURL}`,
    headers: {
        'content-type': 'application/json',
    },
    timeout: 60000 // 请求超时时间
});

// 响应拦截
service.interceptors.response.use((response: any) => {
    const res = response.data;
    if (res.code === 401 || res.code === 434 || res.code === 435|| res.code === 436) {
        ElNotification({
            title: "登录超时",
            message: "登录超时，请重新登录",
            type: "error"
        })
        setTimeout(() => {
            router.push("/log");
        }, 1500)
    } else if (res.code !== 200) {
        ElNotification({
            title: '操作失败',
            message: res.msg,
            type: 'error',
        })
    }
    return res
});

// 返参接口
interface ParameterInterface {
    status: number // 业务状态码
    desc?: string // 业务状态描述
    data: any // 返参数据
}

/**
 * @description: 请求接口
 * @param {string} url
 * @param {Method} method
 * @param {object} data
 * @return {*}
 */
const request = (url: string, method: Method, data?: object, noToken?: boolean): Promise<ParameterInterface> => {
    return new Promise((resolve, reject) => {
        let params = null
        if (method === 'get' ||
            method === 'GET' ||
            method === 'delete' ||
            method === 'DELETE'
        ) {
            params = data
        }
        let options = {
            method,
            url,
            params,
            data,
        }
        if (!noToken) {
            options.headers = {
                Authorization: (localStorage.getItem("tf_admin_token") as string)
            }
        }
        service(options).then(res => {
            console.log(res)
            if (res.code === 200 || res.code === 401) {
                resolve(res)
            } else {
                reject(res)
            }
        })
        .catch(err => {
            reject(err)
        })
    })
}

export default request;